/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.connector.server.prototype;

import com.je.connector.base.config.InstantConfig;
import com.je.connector.server.InstantServer;
import com.je.connector.base.connection.registry.ConnectionRegistry;
import com.je.connector.base.exception.ExceptionHandler;
import com.je.connector.base.message.impl.MessageDispatcher;
import com.je.connector.base.protocol.Command;
import com.je.connector.base.server.NettyTcpServer;
import com.je.connector.server.prototype.handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.Getter;
import java.util.concurrent.TimeUnit;

/**
 * 实现WebSocket服务
 *
 * @ProjectName: instant-message
 * @Package: com.connector.server
 * @ClassName: WebSocketServer
 * @Description: 实现WebSocket服务
 * @Author: LIULJ
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2018</p>
 */
@Getter
public class WebSocketServer extends NettyTcpServer {

    private final ChannelHandler channelHandler;
    private MessageDispatcher messageDispatcher;
    private final InstantServer instantServer;
    private final ConnectionRegistry connectionRegistry;

    public WebSocketServer(InstantServer instantServer) {
        super(InstantConfig.server.websocket.port);
        this.instantServer = instantServer;
        this.messageDispatcher = new MessageDispatcher();
        this.connectionRegistry = instantServer.getConnectionRegistry();
        this.channelHandler = new WebSocketChannelHandler(connectionRegistry, messageDispatcher);
    }

    @Override
    public void init() {
        super.init();
        //消息分发器
        //握手
        messageDispatcher.register(Command.HANDSHAKE, () -> new HandshakeHandler(instantServer));
        //心跳
        messageDispatcher.register(Command.HEARTBEAT, () -> new HeartBeatHandler(instantServer));
        //聊天消息处理
        messageDispatcher.register(Command.PUSH, () -> new PushHandler(instantServer));
        //证书检测
        messageDispatcher.register(Command.HANDSHAKECHECK, () -> new HandShakeCheckHandler(instantServer));
    }

    @Override
    public void start() {
        super.start();
    }

    @Override
    public void stop() {
        super.stop();
    }

    @Override
    public EventLoopGroup getBossGroup() {
        return new NioEventLoopGroup();
    }

    @Override
    public EventLoopGroup getWorkerGroup() {
        return new NioEventLoopGroup();
    }

    @Override
    protected void initPipeline(ChannelPipeline pipeline) {
        pipeline.addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS));
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpObjectAggregator(65536));
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new WebSocketServerProtocolHandler(InstantConfig.server.websocket.wsPath, null, true));
        pipeline.addLast(new WebSocketIndexPageHandler());
        pipeline.addLast(getChannelHandler());
        pipeline.addLast(new HeartBeatServerHandler());
        pipeline.addLast(new ExceptionHandler());
    }

    @Override
    protected void initOptions(ServerBootstrap b) {
        super.initOptions(b);
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.childOption(ChannelOption.SO_SNDBUF, 32 * 1024);
        b.childOption(ChannelOption.SO_RCVBUF, 32 * 1024);
    }

    @Override
    public ChannelHandler getChannelHandler() {
        return channelHandler;
    }

}
